<template>
  <div class="CompetitionDetails-task-table">
    <div style="position: relative">
      <el-button class="exportBtn" @click="exportDetails">导出</el-button>
    </div>

    <el-table :data="State.CompetitionDetailsArr" ref="table" @sort-change="sortChanges"
      :default-sort="{ prop: 'date', order: 'ascending' }" v-if="State.ComType == '5'">
      <el-table-column prop="organizationName" label="参赛单位" min-width="30%"></el-table-column>
      <el-table-column prop="name" label="姓名" min-width="20%"></el-table-column>
      <el-table-column prop="score" label="得分" min-width="20%" :sortable="true"
        :sort-method="(a, b) => ScoreMethod(a, b, 'score')"></el-table-column>
      <el-table-column prop="useTime" label="用时" min-width="20%" :sortable="true"
        :sort-method="(a, b) => UseTimeMethod(a, b, 'useTime')" :formatter="formatter"></el-table-column>
      <!-- <el-table-column prop="option" label="操作" min-width="10%">
        <template #default="scope">
          <el-button @click="ScoreDetails(scope.row, scope.$index)"
            class="CompetitionDetails-task-table-detailed">详情</el-button>
        </template>
</el-table-column> -->
    </el-table>

    <!-- 诊断的是4 -->
    <el-table :data="State.CompetitionDetailsArr" ref="table" @sort-change="sortChanges"
      :default-sort="{ prop: 'date', order: 'ascending' }" v-if="State.ComType != '5'">
      <el-table-column prop="organizationName" label="参赛单位" min-width="30%"></el-table-column>
      <el-table-column prop="name" label="姓名" min-width="20%"></el-table-column>
      <el-table-column prop="score" label="得分" min-width="20%" :sortable="true"
        :sort-method="(a, b) => ScoreMethod(a, b, 'score')"></el-table-column>
      <el-table-column prop="useTime" label="用时" min-width="20%" :sortable="true"
        :sort-method="(a, b) => UseTimeMethod(a, b, 'useTime')" :formatter="formatter"></el-table-column>
      <el-table-column prop="option" label="操作" min-width="10%">
        <template #default="scope">
          <el-button @click="ScoreDetails(scope.row, scope.$index)"
            class="CompetitionDetails-task-table-detailed">详情</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- :default-sort="{ prop: 'date', order: 'ascending' }" v-if="State.ComType != '4'"> 维护和103的是3-->
    <!-- <el-table :data="State.CompetitionDetailsArr" ref="table" @sort-change="sortChanges"
      :default-sort="{ prop: 'date', order: 'ascending' }" v-if="State.ComType == '3'">
      <el-table-column prop="organizationName" label="参赛单位" min-width="30%"></el-table-column>
      <el-table-column prop="name" label="姓名" min-width="20%"></el-table-column>
      <el-table-column prop="score" label="得分" min-width="20%" :sortable="true"
        :sort-method="(a, b) => ScoreMethod(a, b, 'score')"></el-table-column>
      <el-table-column prop="useTime" label="用时" min-width="20%" :sortable="true"
        :sort-method="(a, b) => UseTimeMethod(a, b, 'useTime')" :formatter="formatter"></el-table-column>
      <el-table-column prop="option" label="操作" min-width="10%">
        <template #default="scope">
          <el-button @click="ScoreDetails(scope.row, scope.$index)"
            class="CompetitionDetails-task-table-detailed">详情</el-button>
        </template>
      </el-table-column>
    </el-table> -->

    <!-- 导出字段模板 -->
    <el-table :data="State.CompetitionDetailsArr" style="position: absolute; top:0; left: -200%;" ref="table"
      @sort-change="sortChanges" :default-sort="{ prop: 'date', order: 'ascending' }" id="outDetails">
      <el-table-column :fixed="State.fixs" prop="organizationName" label="参赛单位" min-width="30%"></el-table-column>
      <el-table-column :fixed="State.fixs" prop="name" label="姓名" min-width="20%"></el-table-column>
      <el-table-column :fixed="State.fixs" prop="score" label="得分" min-width="20%" :sortable="true"
        :sort-method="(a, b) => ScoreMethod(a, b, 'score')"></el-table-column>
      <el-table-column :fixed="State.fixs" prop="useTime" label="用时" min-width="20%" :sortable="true"
        :sort-method="(a, b) => UseTimeMethod(a, b, 'useTime')" :formatter="formatter"></el-table-column>
    </el-table>
    <!-- 导出字段模板 -->
  </div>
</template>

<script>
import { defineComponent, reactive, toRef, toRefs, inject, watch, ref, nextTick } from "vue";
import { postData, TimeChange, deepClone } from "@/assets/js/pubilcs.js";
import FileSaver from "file-saver";
import { read, utils, WorkSheet, writeFile, writeFileXLSX, write } from "xlsx";
import bus from "@/bus.js";
import { ElMessage } from 'element-plus'
import HomeContent from '../HomeContent'
export default defineComponent({
  name: "CompetitionDetails",
  components: {},
  props: {
    CompetitionDetailsArr: {
      type: Array,
      default: () => [],
    },
    ComType: {
      type: String,
    },
  },
  setup(props, ctx) {
    let State = reactive({
      CompetitionDetailsArr: [],
      fixs: true,
      //排序状态
      SortState: 0,
      ComType: '',
    });
    //用ref方式获取table的数据
    let table = ref(null)
    nextTick(() => {
      table.value.doLayout()
    })
    //接收父组件传过来的比赛详情的值并赋值
    State.CompetitionDetailsArr = props.CompetitionDetailsArr;
    console.log('State.CompetitionDetailsArr', State.CompetitionDetailsArr);
    State.ComType = props.ComType;
    console.log('State.ComType=========================', State.ComType);
    //监听父组件传过来的比赛详情的值
    watch(() => props.CompetitionDetailsArr, (val, old) => {
      State.CompetitionDetailsArr = val
    },
      { deep: true }
    )
    //排序变化执行的方法
    function sortChanges() {
      if (State.SortState === 1) {
        State.CompetitionDetailsArr = table.value.data;
        //深度克隆数据,不影响原数据
        let B = deepClone(State.CompetitionDetailsArr);
        //对克隆的数据进行排序
        let A = B.sort(CreateCompareFunction("score"));
        //传递给父组件
        ctx.emit("GetCompetitionDetailsArr", A);
      }
      if (State.SortState === 2) {
        State.CompetitionDetailsArr = table.value.data;
        //深度克隆数据,不影响原数据
        let B = deepClone(State.CompetitionDetailsArr);
        //对克隆的数据进行排序
        let A = B.sort(DescendingOrderCreateCompareFunction("useTime"));
        //传递给父组件
        ctx.emit("GetCompetitionDetailsArr", A);
      }
    }
    //降序排列
    function DescendingOrderCreateCompareFunction(propertyName) {
      return function (object1, object2) {
        let value1 = object1[propertyName];
        let value2 = object2[propertyName];
        if (value1 > value2) {
          return 1;
        } else {
          return -1;
        }
      };
    }
    //升序排列
    function CreateCompareFunction(propertyName) {
      return function (object1, object2) {
        let value1 = object1[propertyName];
        let value2 = object2[propertyName];
        if (value1 > value2) {
          return -1;
        } else {
          return 1;
        }
      };
    }
    //分数排序变化执行的方法
    function ScoreMethod(value1, value2, score) {
      // State.SortState = 2;
      State.SortState = 1;
      let a = value1[score];
      let b = value2[score];
      if (a > b) {
        return -1;
      } else {
        return 1;
      }
    }
    //实训使用的时间使用的方法
    function UseTimeMethod(value1, value2, useTime) {
      // State.SortState = 1;
      State.SortState = 2;
      let a = value1[useTime];
      let b = value2[useTime];
      if (a > b) {
        return -1;
      } else {
        return 1;
      }
    }
    //导出
    // function exportDetails() {
    //   let xlsxParam = { raw: true }; //转换成excel时，使用原始的格式
    //   let wb = utils.table_to_book(
    //     document.querySelector("#outDetails"),
    //     xlsxParam
    //   ); //outTable为列表id
    //   let wbout = write(wb, {
    //     bookType: "xlsx",
    //     bookSST: true,
    //     type: "array",
    //   });
    //   try {
    //     FileSaver.saveAs(
    //       new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
    //       "比赛详情.xlsx"
    //     );
    //   } catch (e) {
    //     if (typeof console !== "undefined") console.log(e, wbout);
    //   }
    //   return wbout;
    // }
    function exportDetails() {
      State.fixs = false
      //不加判断table表格导出会有两份数据，是因为fixed造成的，所以要筛选去重
      // 判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去，
      var fix = document.querySelector('.el-table__fixed');
      var exportTable;
      if (fix) {
        exportTable = utils.table_to_book(document.querySelector('#outDetails').removeChild(fix));
        document.querySelector('#outDetails').appendChild(fix);
      } else {
        exportTable = utils.table_to_book(document.querySelector('#outDetails'));
      }
      var exportTableOut = write(exportTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([exportTableOut], { type: 'application/octet-stream' }), '比赛详情.xlsx')
      } catch (e) { if (typeof console !== 'undefined') console.log(e, exportTableOut) }
      State.fixs = true
      return exportTableOut
    }
    //对时间进行处理
    function formatter(row) {
      return TimeChange(row.useTime);
    }
    //具体的比赛详情信息
    function ScoreDetails(row, index) {
      console.log('点击详情', State.MatchPanelState);
      console.log('---------', sessionStorage.getItem('ModelType'));
      console.log('row: ', row, index);
      console.log();
      
      postData("/api/SkillsContest/GetSCResultInfoById", JSON.stringify({ Id: row.resultInfoId }), sessionStorage.getItem("token")).
        then(function (res) {
          // 103的数据在record里，orders里是空的
          if (res.result.result.orders == '') {
            HomeContent.Default.operateRecord.value = JSON.parse(res.result.result.record)
            console.log('103成绩详情操作记录', HomeContent.Default.operateRecord.value);

          } else {
            console.log('+++++++++++=====================', JSON.parse(res.result.result.orders));
            HomeContent.Default.resultInfo.value = JSON.parse(res.result.result.orders)
            HomeContent.Default.player.value = row.name
            // console.log('10333333333', res, res.result, res.result.result, res.result.result.orders);

            if (JSON.parse(res.result.result.orders).Record) {
              HomeContent.Default.ratingForm.value = JSON.parse(res.result.result.orders).Record.RatingForm.RatingForm;
              HomeContent.Default.Synthetical.value = JSON.parse(res.result.result.orders).Record.Synthetical
              console.log('##############3333333');

              HomeContent.Default.FaultRepair.value = JSON.parse(res.result.result.orders).Record.FaultRepair;
              console.log('$$$$$$$$$4444444');

              HomeContent.Default.workOrderSheet.value = JSON.parse(res.result.result.orders).Record.WorkOrderSheet;
              console.log('%%%%%%%%%%%%%%%555555', HomeContent.Default.Synthetical.value);
            }
          }

          console.log('详情页ModelType',sessionStorage.getItem('ModelType'));
          



          // if (res.result.result.orders) {
          if (res.result.result) {
            if (res.success) {
              //传递单人学生详细名字
              sessionStorage.setItem("StudentName", row.name)
              //传递单人学生详情信息
              // GetMatchPanelState -- 12, 新版故障诊断成绩详情
              // GetMatchPanelState -- 7, 新版本拆装
              // GetMatchPanelState -- 4, 旧版故障诊断
              // GetMatchPanelState -- 3, 
              // GetMatchPanelState -- 2, 
              // GetMatchPanelState -- 6, 成绩汇总
              // GetMatchPanelState -- 5, 无成绩详情按钮页面
              // GetMatchPanelState -- 8, 维护详情页面
              // GetMatchPanelState -- 9, 传感器详情页面(103)
              ctx.emit("GetResultDetails", res.result.result)
              if (sessionStorage.getItem('ModelType') == 1) {
                ctx.emit("GetMatchPanelState", 4)
              } else if (sessionStorage.getItem('ModelType') == 12) {
                ctx.emit("GetMatchPanelState", 12)
              } else if (sessionStorage.getItem('ModelType') == 2 || sessionStorage.getItem('ModelType') == 7) {
                ctx.emit("GetMatchPanelState", 7)
              } else if (sessionStorage.getItem('ModelType') == 4) {
                ctx.emit("GetMatchPanelState", 4)
              } else if (sessionStorage.getItem('ModelType') == 3) {
                ctx.emit("GetMatchPanelState", 3)
              } else if (sessionStorage.getItem('ModelType') == 8) {
                ctx.emit("GetMatchPanelState", 8)
              } else if (sessionStorage.getItem('ModelType') == 9) {
                ctx.emit("GetMatchPanelState", 9)
              } 
              ctx.emit("GetMatchBoolean", 0)
            }
          } else {
            ElMessage.warning('暂无数据')
          }
        })
    }
    return {
      State,
      table,
      sortChanges,
      ScoreMethod,
      UseTimeMethod,
      formatter,
      ScoreDetails,
      CreateCompareFunction,
      DescendingOrderCreateCompareFunction,
      exportDetails,
    };
  },
});
</script>
<style lang="less">
.CompetitionDetails-task-table {
  position: absolute;
  width: 96%;
  height: 90%;
  left: 25px;
  top: 50px;
}

.task-tableBox {
  overflow-x: hidden;
  overflow-y: scroll;
}

.task-tableBox::-webkit-scrollbar {
  display: none;
}

.CompetitionDetails-task-table .el-table {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

.el-table::before {
  width: 0 !important;
}

.CompetitionDetails-task-table .el-table .cell {
  text-align: center;
}

.CompetitionDetails-task-table-detailed:hover {
  background: linear-gradient(90deg, #807de1, #218cde);
  color: #ffff;
}

.exportBtn {
  position: absolute;
  top: -40px;
  right: 40px;
  z-index: 999;
}

.exportBtn:hover {
  background: linear-gradient(90deg, #807de1, #218cde);
  color: #ffff;
}
</style>
